package pub.cleangao.memm.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import pub.cleangao.memm.registry.RpcRuntime;
import pub.cleangao.memm.transport.RequestTransport;
import pub.cleangao.memm.transport.RpcServer;
import pub.cleangao.memm.transport.netty.NettyRpcClient;
import pub.cleangao.memm.transport.netty.NettyRpcServer;
import pub.cleangao.memm.util.ThreadPoolFactory;
import java.util.concurrent.ExecutorService;


@Slf4j
@Component
public class RpcServerStarter implements InitializingBean, DisposableBean {

    private final RpcServer nettyRpcServer = new NettyRpcServer();
    private final ExecutorService startThread = ThreadPoolFactory.createThreadPoolIfAbsent("rpc-server");


    @Override
    public void afterPropertiesSet() throws Exception {
        // 1. 启动本地Server
        startThread.execute(nettyRpcServer::start);
        // 2. 设置本地使用的client
        RequestTransport client = NettyRpcClient.getInstance();
        RpcRuntime.setRequestClient(client);
    }

    @Override
    public void destroy() throws Exception {
        // 1. 清除注册信息
        RpcRuntime.downShelf();
        // 2. 关闭本地服务
        nettyRpcServer.close();
    }

}
